package com.example.HaiDLaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.HaiDLaobackend.common.ApiResponse;
import com.example.HaiDLaobackend.entity.ProductEntity;
import com.example.HaiDLaobackend.service.ProductService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/products")
public class ProductController {

	private final ProductService productService;

	public ProductController(ProductService productService) {
		this.productService = productService;
	}

	@GetMapping
	public ApiResponse<Page<ProductEntity>> page(
			@RequestParam(defaultValue = "1") long pageNum,
			@RequestParam(defaultValue = "10") long pageSize,
			@RequestParam(required = false) Long categoryId,
			@RequestParam(required = false) String keyword) {
		LambdaQueryWrapper<ProductEntity> qw = new LambdaQueryWrapper<>();
		qw.eq(categoryId != null, ProductEntity::getCategoryId, categoryId)
			.like(keyword != null && !keyword.isEmpty(), ProductEntity::getTitle, keyword)
			.eq(ProductEntity::getStatus, 1)
			.orderByDesc(ProductEntity::getSales);
		Page<ProductEntity> page = productService.page(new Page<>(pageNum, pageSize), qw);
		return ApiResponse.ok(page);
	}

	@GetMapping("/{id}")
	public ApiResponse<ProductEntity> detail(@PathVariable Long id) {
		ProductEntity entity = productService.getById(id);
		return entity == null ? ApiResponse.error("Not Found") : ApiResponse.ok(entity);
	}

	@GetMapping("/recommend")
	public ApiResponse<List<ProductEntity>> recommend() {
		// 基础随机推荐算法：获取所有上架商品，随机返回12个
		List<ProductEntity> allProducts = productService.list(
			new LambdaQueryWrapper<ProductEntity>()
				.eq(ProductEntity::getStatus, 1)
		);
		
		// 随机打乱
		Collections.shuffle(allProducts);
		
		// 返回前12个
		int count = Math.min(12, allProducts.size());
		List<ProductEntity> recommended = allProducts.subList(0, count);
		
		return ApiResponse.ok(recommended);
	}

	@PostMapping("/{productId}/upload")
	public ApiResponse<String> uploadProductImage(
			@PathVariable Long productId,
			@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return ApiResponse.error("文件为空");
		}
		
		try {
			// 获取项目根目录（pom文件所在目录）
			String projectRoot = System.getProperty("user.dir");
			File productDir = new File(projectRoot, "uploads/products/" + productId);
			if (!productDir.exists()) {
				productDir.mkdirs();
			}
			
			// 生成唯一文件名
			String originalFilename = file.getOriginalFilename();
			String extension = originalFilename != null && originalFilename.contains(".") 
				? originalFilename.substring(originalFilename.lastIndexOf(".")) 
				: ".jpg";
			String filename = UUID.randomUUID().toString() + extension;
			File destFile = new File(productDir, filename);
			
			// 保存文件
			file.transferTo(destFile);
			
			// 返回相对路径
			return ApiResponse.ok("/uploads/products/" + productId + "/" + filename);
		} catch (IOException e) {
			return ApiResponse.error("文件上传失败: " + e.getMessage());
		}
	}
}


